<template>
    <el-card class="form-card">
        <el-form ref="formRef" :model="form" label-width="80px" :rules="rules">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="姓名" prop="fullname">
                <el-input v-model="form.fullname" />
            </el-form-item>
            <el-form-item label="角色">
                <el-select v-model="form.role" placeholder="请选择角色">
                    <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex">
                    <el-radio label="男" />
                    <el-radio label="女" />
                </el-radio-group>
            </el-form-item>
            <el-form-item label="手机" prop="tel">
                <el-input v-model="form.tel" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" />
            </el-form-item>
            <el-form-item label="头像">
                <el-upload class="avatar-uploader" action="http://localhost:3001/upload/common/" :headers="headers"
                    :data="extra" :show-file-list="false" accept=".jpg,.png,.jpeg" :on-success="handleAvatarSuccess"
                    :on-error="handleUploadError" :before-upload="beforeAvatarUpload">
                    <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSubmit(formRef)">保存修改</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import admin from '@/api/admin.js';

let formRef = ref();
let route = useRoute();
console.log(route);
let form = ref({});
let roles = ref([]);
let { id } = route.params;
let loadInfo = async (id) => {
    let { data, status } = await admin.info({ id });
    if (status) {
        return data;
    }
}
// loadInfo(id);
let listLoad = async () => {
    let { status, data, msg } = await admin.role();
    if (status) {
        return data;
    }
}

// listLoad();
let init = async () => {

}
// let init = async () => {
//     let { data: role_list } = await admin.role();
//     roles.value = role_list;
//     let { data: info } = await admin.info({ id })
//     form.value = info;
// }; init();
watch(() => route.params,async (toParams, previousParams) => {
    try {
        roles.value = await listLoad();
        form.value = await loadInfo(toParams.id);
    } catch (error) {
        console.log(error)
    }
},{immediate:true})
let token = sessionStorage.token;
let extra = { type: 'avatar' };
let headers = { Authorization: `Bearer ${token}` };
const handleAvatarSuccess = ({ status, msg, src }, uploadFile) => {
    //上传
    if (status) {
        form.value.avatar = src;
        ElMessage.success(msg);
    }
    else {
        ElMessage.error(msg);
    }
    //生成图片地址

}
let handleUploadError = (error, uploadFile) => {
    let { status, msg } = JSON.parse(error.message);
    ElMessage.error(msg);
}
//判断图片格式

const beforeAvatarUpload = (rawFile) => {
    let isValid = /^image\/(jpeg|png|jpg)$/.test(rawFile.type);
    if (!isValid) {
        ElMessage.error('头像必须是jpg/png格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像体积不能大于 2MB!')
        return false;
    }
    return true;
}


const rules = reactive({
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 30, message: '账户长度要求3-30之间', trigger: 'blur' },
    ],
    tel: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/, message: '请输入11位手机号', trigger: 'blur' },
    ],
    fullname: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 30, message: '姓名至少两个字符', trigger: 'blur' }
    ],
    sex: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    email: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '请输入正确邮箱', trigger: 'blur' },
    ]
});
let router = useRouter();
function handleSubmit(formEl) {console.log(formEl)
    formEl.validate(async (valid, fields) => {
        if (valid) {
            let { status, msg, data } = await admin.change(form.value);
            if (status) {
                ElMessage.success(msg);
                router.push('/admin/list');
            }
            else {
                ElMessage.error(msg)
            }
        } else { ElMessage.error(msg) }
    })
}
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
    